package com.weishi.project.api.controller;

import com.weishi.common.enums.TrainingProgramEnum;
import com.weishi.common.utils.StringUtils;
import com.weishi.framework.web.controller.BaseController;
import com.weishi.framework.web.domain.AjaxResult;
import com.weishi.framework.web.page.TableDataInfo;
import com.weishi.project.api.vo.*;
import com.weishi.project.training.domain.*;
import com.weishi.project.training.service.*;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/app/index")
@Api(value = "ApiIndex", description = "首页统计")
public class ApiIndexController extends BaseController {

    @Autowired
    private ITrainingDayService trainingDayService;

    @Autowired
    private IAnnualPlanService annualPlanService;

    @Autowired
    private ILeaveFormService leaveFormService;

    @Autowired
    private ITrainingWeekService trainingWeekService;

    @Autowired
    private INaturalYearService naturalYearService;

    @Autowired
    private ITrainingAchievementService trainingAchievementService;

    @Autowired
    private ITrainingLocationService trainingLocationService;

    @Autowired
    private ISportsmanMatchService sportsmanMatchService;


    /**
     * 今日训练内容
     */
    @ApiOperation(value = "今日训练内容")
    @ApiImplicitParams({@ApiImplicitParam(name = "day", value = "历史时间", paramType = "path", required = false)})
    @GetMapping("/todayTrainingContent")
    public AjaxResult todayTrainingContent(HttpServletRequest request) throws ParseException {
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String strdate = sf.format(date);
        List<TrainingDay> list = trainingDayService.selectTrainingDayListByDay(strdate);
        List<Map<String, Object>> rets = new ArrayList<>();
        for (TrainingDay day : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", day.getId());
            map.put("weekId", day.getWeekId());
            map.put("dayWeek", day.getDayWeek());
            map.put("fourSeasons", day.getFourSeasons());
            map.put("firstLevel", day.getFirstLevel());
            map.put("secondLevel", day.getSecondLevel());
            map.put("kilometers", day.getKilometers());
            map.put("idealKilometers", day.getIdealKilometers());
            map.put("sr", day.getSr());
            map.put("hr", day.getHr());
            map.put("numberGroups", day.getNumberGroups());
            map.put("day", day.getDay());
            map.put("gapTime", day.getGapTime());
            map.put("strength", day.getStrength());
            map.put("score", String.valueOf(day.getScore()));
            map.put("startTime", day.getStartTime());
            map.put("endTime", day.getEndTime());
            map.put("ctime", day.getCtime());
            map.put("weekName", day.getWeekName());
            map.put("firstLevelName", day.getFirstLevelName());
            map.put("secondLevelName", day.getSecondLevelName());
            rets.add(map);
        }
        return AjaxResult.success(rets);
    }

    @ApiOperation(value = "阶段目标完成情况")
    @ApiImplicitParams({@ApiImplicitParam(name = "naturalYearId", value = "历史时间", paramType = "path", required = false)})
    @GetMapping("/annualTargetCompletionRate")
    public AjaxResult annualTargetCompletionRate(HttpServletRequest request) {
        int naturalYearId = 0;
        if (request.getParameter("naturalYearId") != null) {
            naturalYearId = Integer.parseInt(request.getParameter("naturalYearId"));
        } else {
            return AjaxResult.error("请选择年度");
        }
        AnnualPlan annualPlan = new AnnualPlan();
        annualPlan.setNaturalYearId(naturalYearId);
        List<AnnualPlan> list = annualPlanService.selectAnnualPlanList(annualPlan);
        Map<String, Object> map = new HashMap<>();
        map.put("annualPlan", list); //年度训练计划
        return AjaxResult.success(map);
    }

    /**
     * 年度训练比赛地点
     */
    @ApiOperation(value = "年度训练/比赛地点")
    @GetMapping("/trainingArea")
    public AjaxResult trainingArea(HttpServletRequest request) {
        int naturalYearId = 0;
        NaturalYear naturalYear = null;
        if (request.getParameter("naturalYearId") != null) {
            naturalYearId = Integer.parseInt(request.getParameter("naturalYearId"));
            naturalYear = naturalYearService.getById(naturalYearId);
        }
        if (request.getParameter("type") == null) {
            return AjaxResult.error("请选择类型");
        }
        TrainingLocation trainingLocation = new TrainingLocation();
        trainingLocation.setType(Integer.parseInt(request.getParameter("type")));
        if (trainingLocation.getType() == 1) {
            Map<String,Object> params = new HashMap<>();
            if(naturalYear!=null){
                params.put("startTime", naturalYear.getStartTime());
                params.put("endTime", naturalYear.getEndTime());
            }
            params.put("type",1);

            List<TrainingLocation> list = trainingLocationService.selectTrainingLocationListByMap(params);
            return AjaxResult.success(list);
        } else {
            List<TrainingLocation> list = trainingLocationService.selectTrainingLocationList(trainingLocation);
            Map<String, Object> countMap = new HashMap<>();
            Map<String, Object> weekCountMap = new HashMap<>();
            if (naturalYear !=null && naturalYear.getStartTime() != null) {
                countMap.put("startTime", naturalYear.getStartTime());
                countMap.put("endTime", naturalYear.getEndTime());
                weekCountMap.put("startTime", naturalYear.getStartTime());
                weekCountMap.put("endTime", new Date());
            }else{
                weekCountMap.put("startTime","2000-01-01 00:00:00");
                weekCountMap.put("endTime", new Date());
            }

            for (TrainingLocation location : list) {
                countMap.put("adress", location.getVenue());
                weekCountMap.put("adress", location.getVenue());
                int count = trainingLocationService.getTrainingLocationCount(countMap);
                int weekCount = trainingLocationService.getTrainingLocationCount(weekCountMap);
                location.setLocationCount(count);
                location.setWeekCount(weekCount);
            }
            return AjaxResult.success(list);
        }
    }

    @ApiOperation(value = "各训练项目完成进度-折线图")
    @ApiImplicitParams({@ApiImplicitParam(name = "naturalYearId", value = "历史时间", paramType = "path", required = false)})
    @GetMapping("/trainingProgramSchedule")
    public AjaxResult trainingProgramSchedule(HttpServletRequest request) {
        int naturalYearId = 0;
        if (request.getParameter("naturalYearId") != null) {
            naturalYearId = Integer.parseInt(request.getParameter("naturalYearId"));
        } else {
            return AjaxResult.error("请选择年度");
        }
        String firstLevel1 = "special_training_water";
        TrainingDayDetailsVo trainingDayDetailsVo = new TrainingDayDetailsVo();
        trainingDayDetailsVo.setLevel(firstLevel1);
        trainingDayDetailsVo.setNaturalYearId(naturalYearId);
        //水上专项训练
        List<TrainingDayDetailsVo> data1 = trainingDayService.getTrainingDayListDetails(trainingDayDetailsVo);

        String firstLevel2 = "land_specific_training_dynamometer";
        TrainingDayDetailsVo trainingDayDetailsVo2 = new TrainingDayDetailsVo();
        trainingDayDetailsVo2.setLevel(firstLevel2);
        trainingDayDetailsVo2.setNaturalYearId(naturalYearId);
        //陆上专项训练
        List<TrainingDayDetailsVo> data2 = trainingDayService.getTrainingDayListDetails(trainingDayDetailsVo2);


        Map<String, List<TrainingDayDetailsVo>> ret = new HashMap<>();
        ret.put(TrainingProgramEnum.WATERPROJECT.getKey(), data1);
        ret.put(TrainingProgramEnum.LANDSPECIFICTRAININGDYNAMOMETER.getKey(), data2);

        return AjaxResult.success(ret);
    }

    /**
     * 男子训练成绩TOP10
     */
    @ApiOperation(value = "男子训练成绩TOP10")
    @PostMapping("/trainingResultsMan")
    public AjaxResult trainingResultsMan(@RequestBody Map<String, Object> params) {
        /**
         * 接收排序的传参 1==降序   0==升序
         */
        int value1 = Integer.parseInt(params.get("trainingMode").toString());

        params.put("sex",0);
        List<TrainingAchievementTopVo> trainingAchievementTopVos = trainingAchievementService.qryTrainingAchievementTop(params);
        for (int i = 0; i < trainingAchievementTopVos.size(); i++) {
            if (StringUtils.isEmpty(trainingAchievementTopVos.get(i).getAchievement())) {
                trainingAchievementTopVos.remove(trainingAchievementTopVos.get(i));
                i--;
            }
        }

        /**
         * 对 List 数组进行排序
         */
        if(value1 == 1){
            //降序
            Collections.sort(trainingAchievementTopVos, new Comparator<TrainingAchievementTopVo>() {
                @Override
                public int compare(TrainingAchievementTopVo o1, TrainingAchievementTopVo o2) {
                    return o2.getAchievement().compareTo(o1.getAchievement());
                }
            });
            return AjaxResult.success(trainingAchievementTopVos);
        }else{
            //升序
            Collections.sort(trainingAchievementTopVos, new Comparator<TrainingAchievementTopVo>() {
                @Override
                public int compare(TrainingAchievementTopVo o1, TrainingAchievementTopVo o2) {
                    return o1.getAchievement().compareTo(o2.getAchievement());
                }
            });
            return AjaxResult.success(trainingAchievementTopVos);
        }
    }

    /**
     * 女子训练成绩TOP10
     */
    @ApiOperation(value = "女子训练成绩TOP10")
    @PostMapping("/trainingResultsWoman")
    public AjaxResult trainingResultsWoman(@RequestBody Map<String, Object> params) {
        /**
         * 接收排序的传参 1==降序   0==升序
         */
        int value1 = Integer.parseInt(params.get("trainingMode").toString());

        params.put("sex",1);
        List<TrainingAchievementTopVo> trainingAchievementTopVos = trainingAchievementService.qryTrainingAchievementTop(params);
        for (int i = 0; i < trainingAchievementTopVos.size(); i++) {
            if (StringUtils.isEmpty(trainingAchievementTopVos.get(i).getAchievement())) {
                trainingAchievementTopVos.remove(trainingAchievementTopVos.get(i));
                i--;
            }
        }

        /**
         * 对 List 数组进行排序
         */
        if(value1 == 1){
            //降序
            Collections.sort(trainingAchievementTopVos, new Comparator<TrainingAchievementTopVo>() {
                @Override
                public int compare(TrainingAchievementTopVo o1, TrainingAchievementTopVo o2) {
                    return o2.getAchievement().compareTo(o1.getAchievement());
                }
            });
            return AjaxResult.success(trainingAchievementTopVos);
        }else{
            //升序
            Collections.sort(trainingAchievementTopVos, new Comparator<TrainingAchievementTopVo>() {
                @Override
                public int compare(TrainingAchievementTopVo o1, TrainingAchievementTopVo o2) {
                    return o1.getAchievement().compareTo(o2.getAchievement());
                }
            });
            return AjaxResult.success(trainingAchievementTopVos);
        }

    }

    /**
     * 阶段伤病及考情状态——人数统计
     */
    @ApiOperation(value = "阶段伤病及考情状态——人数统计")
    @GetMapping("/checkOnWorkAttendancePopulationStatistics")
    public AjaxResult checkOnWorkAttendancePopulationStatistics(@RequestParam Date weekPlanStartTime, @RequestParam Date weekPlanEndTime) {
        //查询指定日期内不同状态如请假，生病等累计总人数
        //可传周期id 通过周期id 查询时间 放入map
        Map<String, Object> map = new HashMap<>();
        map.put("weekPlanStartTime", weekPlanStartTime);
        map.put("weekPlanEndTime", weekPlanEndTime);
        return AjaxResult.success(leaveFormService.getPeopleCount(map));
    }

    /**
     * 阶段伤病及考情状态——周型统计
     */
    @ApiOperation(value = "阶段伤病及考情状态——周型统计")
    @GetMapping("/checkOnWorkAttendanceWeekTypeStatistics")
    public AjaxResult checkOnWorkAttendanceWeekTypeStatistics(@RequestParam Date weekPlanStartTime, @RequestParam Date weekPlanEndTime) {
        //查询指定日期内不同周型如基本周，积累周等累计总周数
        //可传周期id 通过周期id 查询时间 放入map
        Map<String, Object> map = new HashMap<>();
        map.put("weekPlanStartTime", weekPlanStartTime);
        map.put("weekPlanEndTime", weekPlanEndTime);
        return AjaxResult.success(trainingWeekService.queryWeekTypeCount(map));
    }


    /**
     * 阶段伤病及考情状态——报表统计
     */
    @ApiOperation(value = "阶段伤病及考情状态——报表统计")
    @GetMapping("/checkOnWorkAttendanceReportStatistics")
    public AjaxResult checkOnWorkAttendanceReportStatistics(@RequestParam int year, @RequestParam String type) {
        //查询指定年，每个月对应类型分别有多少人（类型包含请假，受伤，生病等）
        Map<String, Object> map = new HashMap<>();
        map.put("year", year);
        map.put("type", type);
        List<PeopleEveryMonth> list = leaveFormService.queryCount(map);
        return AjaxResult.success(list);
    }

    /**
     * 阶段伤病及考情状态——列表统计
     */
    @ApiOperation(value = "阶段伤病及考情状态——列表统计")
    @GetMapping("/checkOnWorkAttendanceTableStatistics")
    public TableDataInfo checkOnWorkAttendanceTableStatistics(LeaveForm leaveForm) {
        startPage();
        if(leaveForm.getNaturalYearId()!=0){
            NaturalYear naturalYear = naturalYearService.getById(leaveForm.getNaturalYearId());
            Date startTime = naturalYear.getStartTime();
            Date endTime = naturalYear.getEndTime();
            leaveForm.setStartTime(startTime);
            leaveForm.setEndTime(endTime);
        }
        List<LeaveForm> list = leaveFormService.selectLeaveFormList(leaveForm);
        for (LeaveForm lf : list) {
            //如果治愈时间 即 归队时间在当前时间之前 那么状态则为康复 置为1 反之 为治疗中 置为0
            if (lf.getCureTime()!=null && lf.getCureTime().before(new Date())) {
                lf.setNowStatus(1);
            } else {
                lf.setNowStatus(0);
            }
        }
        return getDataTable(list);
    }

    @ApiOperation(value = "今日受伤，生病，过敏等人数统计")
    @GetMapping("/getCountByDay")
    public AjaxResult getCountByDay(int type) {
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        return AjaxResult.success(leaveFormService.getCountByDay(map));
    }

    @ApiOperation(value = "本周受伤，生病，过敏等人数统计")
    @GetMapping("/getCountByWeek")
    public AjaxResult getCountByTime(int type) {
        TrainingWeek trainingWeek = leaveFormService.getWeekIdByNowDate();
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", trainingWeek.getStartTime());
        map.put("endTime", trainingWeek.getEndTime());
        map.put("type", type);
        return AjaxResult.success(leaveFormService.getCountByTime(map));
    }

    @ApiOperation(value = "本年度受伤，生病，过敏等人数统计")
    @GetMapping("/getCountByYear")
    public AjaxResult getCountByYear(int type) {
        NaturalYear naturalYear = leaveFormService.getCountByYear();
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", naturalYear.getStartTime());
        map.put("endTime", naturalYear.getEndTime());
        map.put("type", type);
        return AjaxResult.success(leaveFormService.getCountByTime(map));
    }

    @ApiOperation(value = "各类型每月发生次数统计-折线图")
    @GetMapping("/leaveFormTypeCount")
    public AjaxResult leaveFormTypeCount(@ApiParam(name = "sportsmanId", value = "运动员Id") @RequestParam("sportsmanId") Integer sportsmanId,
                                         @ApiParam(name = "type", value = "类型") @RequestParam("type") Integer type,
                                         @ApiParam(name = "naturalYearId", value = "年度ID") @RequestParam("naturalYearId") int naturalYearId) {
        NaturalYear naturalYear = naturalYearService.getById(naturalYearId);
        Date startTime1 = naturalYear.getStartTime();
        Date endTime = naturalYear.getEndTime();
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", startTime1);
        map.put("endTime", endTime);
        map.put("sportsmanId", sportsmanId);
        map.put("type", type);
        return AjaxResult.success(leaveFormService.getLeaveFormTypeVoCount(map));
    }

    @ApiOperation(value = "各类型各个属性展示-列表")
    @GetMapping("/getSportsInjuryVoList")
    public AjaxResult getSportsInjuryVoList(@ApiParam(name = "type", value = "类型") @RequestParam("type") Integer type) {
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        List<SportsInjuryVo> injurylist = leaveFormService.getSportsInjuryVoList(map);
        for (SportsInjuryVo sportsInjuryVo : injurylist) {
            //如果治愈时间 即 归队时间在当前时间之前 那么状态则为康复 置为1 反之 为治疗中 置为0
            if (sportsInjuryVo.getReturnTime().before(new Date())) {
                sportsInjuryVo.setNowStatus(1);
            } else {
                sportsInjuryVo.setNowStatus(0);
            }
        }
        return AjaxResult.success(injurylist);
    }


    @ApiOperation(value = "各受伤部位发生量")
    @GetMapping("/getInjuryCountVoList")
    public AjaxResult getInjuryCountVoList(@ApiParam(name = "naturalYearId", value = "年度ID") @RequestParam("naturalYearId") int naturalYearId) {
        NaturalYear naturalYear = naturalYearService.getById(naturalYearId);
        Date startTime = naturalYear.getStartTime();
        Date endTime = naturalYear.getEndTime();
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        List<LeaveFormInjuryVo> list = leaveFormService.getLeaveFormInjuryVo(map);
        return AjaxResult.success(list);
    }

    @ApiOperation(value = "各受伤部位占比")
    @GetMapping("/getInjuryCountVoListTwo")
    public AjaxResult getInjuryCountVoListTwo(@ApiParam(name = "type", value = "类型") @RequestParam("type") Integer type,
                                              @ApiParam(name = "naturalYearId", value = "年度ID") @RequestParam("naturalYearId") int naturalYearId) {
        NaturalYear naturalYear = naturalYearService.getById(naturalYearId);
        Date startTime1 = naturalYear.getStartTime();
        Date endTime = naturalYear.getEndTime();
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", startTime1);
        map.put("endTime", endTime);
        map.put("type", type);
        return AjaxResult.success(leaveFormService.getInjuryCountVoList(map));
    }

    @ApiOperation(value = "查看离队,生病,请假,受伤详情信息")
    @GetMapping("/getLeaveFormDetails")
    public AjaxResult getLeaveFormDetails(@ApiParam(name = "id", value = "id") @RequestParam("id") Integer id) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        return AjaxResult.success(leaveFormService.getLeaveFormDetails(map));
    }
}
